<template>
  <div class="login">
    <el-form ref="loginFormRef" :model="loginForm" :rules="loginRules" class="login-form">
      <h3 class="title">Piece 考试</h3>
      <el-form-item prop="uname">
        <el-input ref="uname" v-model="loginForm.uname" tabindex="1" type="text" auto-complete="off" placeholder="登录账号">
          <svg-icon slot="prefix" icon-class="user" class="el-input__icon input-icon" />
        </el-input>
      </el-form-item>
      <el-form-item prop="nname">
        <el-input v-model="loginForm.nname" tabindex="2" type="text" auto-complete="off" placeholder="昵称">
          <svg-icon slot="prefix" icon-class="user" class="el-input__icon input-icon" />
        </el-input>
      </el-form-item>
      <el-form-item prop="email">
        <el-input v-model="loginForm.email" type="text" auto-complete="off" placeholder="邮箱">
          <svg-icon slot="prefix" icon-class="email" class="el-input__icon input-icon" />
        </el-input>
      </el-form-item>
      <el-tooltip v-model="capsTooltip" content="大写锁定已打开" placement="right" manual>
        <el-form-item prop="pword">
          <span class="svg-container">
            <svg-icon icon-class="password" />
          </span>
          <el-input
            :key="passwordType"
            ref="pword"
            v-model.trim="loginForm.pword"
            :type="passwordType"
            tabindex="3"
            placeholder="密码"
            @keyup.native="checkCapslock"
            @blur="capsTooltip = false"
          />
          <span
            v-if="passwordType === 'password'"
            class="show-password"
            @click="handlePassword"
          >
            <svg-icon icon-class="eye" />
          </span>
          <span v-else class="show-password" @click="handlePassword">
            <svg-icon icon-class="eye-open" />
          </span>
        </el-form-item>
      </el-tooltip>
      <el-tooltip v-model="capsTooltip" content="大写锁定已打开" placement="right" manual>
        <el-form-item prop="repword">
          <span class="svg-container">
            <svg-icon icon-class="password" />
          </span>
          <el-input
            :key="passwordType2"
            ref="repword"
            v-model.trim="loginForm.repword"
            :type="passwordType2"
            tabindex="3"
            placeholder="密码"
            @keyup.native="checkCapslock"
            @blur="capsTooltip = false"
          />
          <span
            v-if="passwordType2 === 'password'"
            class="show-password"
            @click="handlePassword2"
          >
            <svg-icon icon-class="eye" />
          </span>
          <span v-else class="show-password" @click="handlePassword2">
            <svg-icon icon-class="eye-open" />
          </span>
        </el-form-item>
      </el-tooltip>
      <el-form-item v-if="loginForm.oauthType" prop="verify">
        <el-input
          v-model="loginForm.captchaCode"
          auto-complete="off"
          placeholder="验证码"
          style="width: 63%"
          @keyup.enter.native="handleRegister"
        >
          <svg-icon slot="prefix" icon-class="validCode" class="el-input__icon input-icon" />
        </el-input>
        <div class="login-code">
          <img ref="verify_code" style="width: 130px;cursor: pointer;" alt="点击切换" :src="verifyUrl" @click="getVerifyCode">
        </div>
      </el-form-item>
      <el-form-item style="width:100%;">
        <el-button
          :loading="loading"
          class="login-btn"
          size="medium"
          type="primary"
          style="width:100%;"
          @click.native.prevent="handleRegister"
        >
          注 册
        </el-button>
      </el-form-item>
    </el-form>
    <!--  底部  -->
    <div class="el-login-footer">
      <span>Copyright © {{ copyright }} {{ siteName }} All Rights Reserved.</span>
    </div>
  </div>
</template>

<script>
import { getUUID } from '@/utils/auth'
import { validLoginName, validatePassword, validUserName, validEmail } from '@/utils/validate'

export default {
  name: 'Register',
  directives: {
    focus: {
      inserted(el) {
        el.querySelector('input').focus()
      }
    }
  },
  data() {
    const validIdentical = (rule, value, callback) => {
      if (value && value === this.loginForm.pword) {
        callback()
      }
      callback(new Error(rule.message))
    }

    return {
      loginForm: {
        captcha_token: '',
        uname: undefined,
        nname: undefined,
        email: undefined,
        pword: undefined,
        repword: undefined,
        verify: undefined,
        oauthType: undefined,
        code: undefined,
        oauthUserId: undefined,
        accessToken: undefined,
        expireIn: undefined,
        refreshToken: undefined,
        avatar: undefined,
        nickname: undefined,
        sex: undefined,
        captchaCode: undefined
      },
      loginRules: {
        uname: [
          { required: true, trigger: 'blur', message: '登录账号不能为空' },
          { trigger: 'blur', validator: validLoginName }
        ],
        nname: [
          { required: true, trigger: 'blur', message: '昵称不能为空' },
          { trigger: 'blur', validator: validUserName }
        ],
        email: [
          { required: true, trigger: 'blur', message: '邮箱不能为空' },
          { trigger: 'blur', validator: validEmail }
        ],
        pword: [
          { required: true, trigger: 'blur', message: '密码不能为空' },
          { trigger: 'blur', validator: validatePassword }
        ],
        repword: [
          { required: true, trigger: 'blur', message: '确认密码不能为空' },
          { validator: validIdentical, trigger: 'blur', message: '确认密码与密码不一致' }
        ],
        captchaCode: [{ required: true, trigger: 'change', message: '验证码不能为空' }]
      },
      loading: false,
      passwordType: 'password',
      passwordType2: 'password',
      capsTooltip: false,
      redirect: undefined,
      verifyUrl: undefined,
      siteName: '',
      copyright: ''
    }
  },
  watch: {
    $route: {
      handler: function(route) {
        this.redirect = route.query && route.query.redirect
        this.loginForm.oauthType = route.query && route.query.oauthType
        this.loginForm.code = route.query && route.query.code
        this.loginForm.oauthUserId = route.query && route.query.oauthUserId
        this.loginForm.accessToken = route.query && route.query.accessToken
        this.loginForm.expireIn = route.query && route.query.expireIn
        this.loginForm.refreshToken = route.query && route.query.refreshToken
        this.loginForm.avatar = route.query && route.query.avatar
        this.loginForm.nickname = route.query && route.query.nickname
        this.loginForm.sex = route.query && route.query.sex
      },
      immediate: true
    }
  },
  created() {
    document.body.style.overflow = 'hidden'
  },
  mounted() {
    const this_ = this
    this.loginForm.captcha_token = getUUID()
    this.getFooterInfo()

    if (this.loginForm.uname === '') {
      this.$refs.uname.focus()
    }

    if (this.loginForm.oauthType) {
      this.getVerifyCode()
      setTimeout(() => {
        this_.$refs.verify_code.click()
      }, 1000)
    }
  },
  methods: {
    handlePassword() {
      this.passwordType === 'password'
        ? (this.passwordType = '')
        : (this.passwordType = 'password')
      this.$nextTick(() => {
        this.$refs.pword.focus()
      })
    },
    handlePassword2() {
      this.passwordType2 === 'password'
        ? (this.passwordType2 = '')
        : (this.passwordType2 = 'password')
      this.$nextTick(() => {
        this.$refs.repword.focus()
      })
    },
    checkCapslock(e) {
      const { key } = e
      this.capsTooltip = key && key.length === 1 && (key >= 'A' && key <= 'Z')
    },
    getFooterInfo() {
      this.$http.get('/footer/info').then(response => {
        this.siteName = response.param.siteName
        this.copyright = response.param.copyright
      }).catch(e => {})
    },
    getVerifyCode() {
      this.verifyUrl = this.$store.state.app.server_api + '/authentication/code/captcha?type=char&captcha_token=' + this.loginForm.captcha_token + '&r=' + Math.random()
    },
    handleRegister() {
      this.$refs.loginFormRef.validate(valid => {
        if (valid) {
          this.loading = true
          const dispatch = this.loginForm.oauthType ? 'user/bindOauth' : 'user/signUp'
          this.$store.dispatch(dispatch, this.loginForm).then((response) => {
            if (response.token) {
              this.$router.push({ path: this.redirect || '/' })
            } else {
              this.$message({
                type: 'success',
                message: response.message
              })
              this.$router.push({ path: `/login?redirect=${this.redirect}` })
            }
            this.loading = false
          }).catch(() => {
            this.loading = false
            this.getVerifyCode()
          })
        } else {
          return false
        }
      })
    }
  }
}
</script>

<style rel="stylesheet/scss" lang="scss">
  .login {
    display: flex;
    justify-content: center;
    align-items: center;
    height: 100%;
    background-image: url("~@/assets/login-background.jpg");
    background-size: cover;
  }
  .title {
    margin: 0px auto 30px auto;
    text-align: center;
    color: #707070;
  }

  .login-form {
    border-radius: 6px;
    background-color: rgba(255,255,255,0.4);
    width: 400px;
    padding: 25px 25px 5px 25px;
    .el-input {
      height: 38px;
      input {
        height: 38px;
      }
    }
    .input-icon {
      height: 39px;
      width: 14px;
      margin-left: 2px;
    }
  }
  .login-tip {
    font-size: 13px;
    text-align: center;
    color: #bfbfbf;
  }
  .svg-container {
    position: absolute;
    top: 7px;
    left: 6px;
    z-index: 999;
    font-size: 16px;
    color: #C0C4CC;
    cursor: pointer;
    user-select: none;
  }
  .svg-container + .el-input {
    input {
      padding-left: 30px;
    }
  }
  .show-password {
    position: absolute;
    top: 7px;
    right: 25px;
    font-size: 16px;
    color:#C0C4CC;
    cursor: pointer;
    user-select: none;
  }
  .login-code {
    width: 33%;
    height: 38px;
    float: right;
    img {
      cursor: pointer;
      vertical-align: middle;
    }
  }
  .el-login-footer {
    height: 40px;
    line-height: 40px;
    position: fixed;
    bottom: 0;
    width: 100%;
    text-align: center;
    background-color: rgba(255,255,255,0.4);
    font-family: Arial;
    font-size: 12px;
    letter-spacing: 1px;
  }
</style>
